package com.lins.framework.utils.down.dialog;


import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lins.framework.R;
import com.lins.framework.common.Constants;
import com.lins.framework.mvpframe.rx.RxBus;
import com.lins.framework.mvpframe.rx.RxSchedulerHelper;
import com.lins.framework.utils.down.bean.Download;

import rx.functions.Action1;

/**
 * Created by Administrator on 2018/1/29.
 */

public class DownloadDialogFragment extends DialogFragment {

    private ProgressBar idPb;
    private TextView idTvPb;

    public static DownloadDialogFragment newInstance() {

        Bundle args = new Bundle();

        DownloadDialogFragment fragment = new DownloadDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_download, null);

        idPb = view.findViewById(R.id.id_pb);
        idTvPb = view.findViewById(R.id.id_tv_pb);
        builder.setView(view);
        return builder.create();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(false);
        RxBus.$().<Download>register(Constants.RXBUS_DOWNLOAD_APK)
                .onBackpressureDrop()//背压
                .compose(RxSchedulerHelper.<Download>io_main())
                .subscribe(new Action1<Download>() {
                    @Override
                    public void call(Download download) {
                        idPb.setProgress(download.getProgress());
                        idTvPb.setText(download.getProgress() + "%");
                        if (download.getProgress() == 100) {
                            dismiss();
                        }
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.$().unregister(Constants.RXBUS_DOWNLOAD_APK);
    }
}
